<template>
  <div style="margin-top: 10px;">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-left:15px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>科室管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top: 10px;">
      <el-row id="inputs" style="margin-left: 18px;" :gutter="20">
        <el-col :span="10">
          <div class="grid-content bg-purple-dark">
            <el-input placeholder="请输入科室名称" v-model="text" clearable />
          </div>
        </el-col>
        <el-button type="primary" icon="el-icon-search" @click="go(text)">查询</el-button>
        <el-button type="primary" style="margin-left:5px;" @click="add()">新增科室</el-button>
        <el-button type="warning" style="margin-left:5px;" @click="getSelectExcel()">全部导出</el-button>
        <el-button
          type="danger"
          style="margin-left:5px;"
          v-show="multipleSelection!=null&&multipleSelection!=''"
          @click="deletes()"
        >批量删除</el-button>
      </el-row>
    </el-card>
    <el-card style="margin-top: 10px;">
      <el-row>
        <el-main style="margin-top: -30px;">
          <el-table
            :data="departmentInformation"
            border
            stripe
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            :row-key="getRowKey"
          >
            <el-table-column prop="id" type="selection" width="50" align="center" :reserve-selection="true"></el-table-column>
            <el-table-column prop="deptcode" label="科室编码" width="100" align="center"></el-table-column>
            <el-table-column prop="deptname" label="科室名称" align="center"></el-table-column>
            <el-table-column prop="deptcategoryidname" label="科室分类" width="140" align="center"></el-table-column>
            <el-table-column prop="depttypemodlename" label="科室类型" width="100" align="center"></el-table-column>
            <el-table-column label="操作" width="180px" align="center">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  content="编辑"
                  icon="el-icon-edit"
                  size="mini"
                  @click="modifyDepartment(scope.row)"
                >编辑</el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  content="删除"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteDepartment(scope.row.id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            small
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :total="total"
          ></el-pagination>
          <!-- 添加用户的对话框 -->
          <el-dialog
            title="添加科室"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="addDialogVisibleerAddFormRef"
          >
            <el-form :model="addForm" ref="addFormRef" label-width="70px">
              <el-form-item label="科室类别" prop="depttype">
                <el-select v-model="addForm.depttype" 
                clearable filterable 
                placeholder="请选择活动区域" 
                @change="SelectDepartmentList"
                >
                  <el-option
                    v-for="de in deptTypeList"
                    :key="de.value"
                    :label="de.name"
                    :value="de.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="科室分类" prop="deptcategoryid">
                <el-select
                  v-model="addForm.deptcategoryid"
                  clearable
                  filterable
                  placeholder="请选择活动区域"
                >
                  <el-option
                    v-for="de in DepartmentList"
                    :key="de.value"
                    :label="de.constantName"
                    :value="de.constantId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="科室编码" prop="deptcode">
                <el-input v-model="addForm.deptcode"></el-input>
              </el-form-item>
              <el-form-item label="科室名称" prop="deptname">
                <el-input v-model="addForm.deptname"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancel('addFormRef')">取 消</el-button>
              <el-button type="primary" @click="insert()">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 编辑表单 rules:验证规则  ref:模型（目前）-->
          <el-dialog
            title="编辑科室"
            :visible.sync="departmentEditor"
            width="50%"
            @close="addDialogVisibleerDepartmentEditorDataRef"
          >
            <el-form :model="departmentEditorData" ref="departmentEditorDataRef" label-width="70px">
              <el-form-item label="科室编码" prop="deptcode">
                <el-input v-model="departmentEditorData.deptcode"></el-input>
              </el-form-item>
              <el-form-item label="科室名称" prop="deptname">
                <el-input v-model="departmentEditorData.deptname"></el-input>
              </el-form-item>
              <el-form-item label="科室分类" prop="deptcategoryid">
                <el-select
                  v-model="departmentEditorData.deptcategoryid"
                  filterable
                  clearable
                  placeholder="请选择活动区域"
                  @change="SelectDepartmentList"
                >
                  <el-option
                    v-for="de in deptTypeList"
                    :key="de.value"
                    :label="de.name"
                    :value="de.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="科室类别" prop="id">
                <el-select
                  v-model="departmentEditorData.id"
                  filterable
                  clearable
                  placeholder="请选择活动区域"
                >
                  <el-option
                    v-for="de in DepartmentList"
                    :key="de.value"
                    :label="de.constantName"
                    :value="de.constantId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancel('departmentEditorDataRef')">取 消</el-button>
              <el-button type="primary" @click="updateByPrimaryKeySelective()">确 定</el-button>
            </span>
          </el-dialog>
        </el-main>
      </el-row>
    </el-card>
  </div>
</template>
<script>
export default {
  created() {
    this.addForm = {
      deptcode: "",
      deptname: "",
      deptcategoryid: "",
      depttype: "",
    };
    this.departmentEditorData = {
      deptcode: "",
      deptname: "",
      deptcategoryid: "",
      id: "",
    };
    this.getUserList();
    this.addDepartment();
    this.selectDeptType();
    this.SelectDepartmentList();
  },
  data() {
    return {
      //绑定输入框
      text: "",
      //页面总页数
      pageSize: 10,
      //页面表格
      departmentInformation: [],
      //批量删除数组
      multipleSelection: [],
      //添加的表单
      addForm: {},
      //添加表单开启属性
      addDialogVisible: false,
      //修改表单开启属性
      departmentEditor: false,
      //修改的表单
      departmentEditorData: {},
      //单独删除的id
      deletesId: [],
      //科室列表集合[]
      deptTypeList: [],

      pagingTools: "",
      //当前页码
      pageNum: "",
      //总记录数y
      
      total: 0,
      //总页数
      totalPage: "",
      //科室分类集合
      DepartmentList: [],
    };
  },
  methods: {
    //查询全部方法（初始加载）
    async getUserList() {
      const { data: res } = await this.$http.post(
        "departmentController/SelectDepartmentAll",
        {
          pageNum: 1,
          pageSize: 10,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.departmentInformation = res.data.list;
      this.pageNum = res.data.pageNum;
      this.total = res.data.total;
      this.totalPage = res.data.totalPage;
      this.$forceUpdate();
    },
    //查询全部方法（点击页码）
    async handleCurrentChange(val) {
      console.log(this.text);
      if (this.text == "") {
        const { data: res } = await this.$http.post(
          "departmentController/SelectDepartmentAll",
          {
            pageNum: val,
            pageSize: 10,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户列表失败！");
        }
        this.departmentInformation = res.data.list;
        this.pageNum = res.data.pageNum;
        this.total = res.data.total;
        this.totalPage = res.data.totalPage;
      } else {
        const { data: res } = await this.$http.post(
          "departmentController/departmentFuzzyByName",
          {
            condition:"department.DeptName",
            name: this.text,
            pageNum: val,
            pageSize: 10,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户列表失败！");
        }
        this.departmentInformation = res.data.list;
        this.pageNum = res.data.pageNum;
        this.total = res.data.total;
        this.totalPage = res.data.totalPage;
      }
    },
    //模糊查询方法
    async go(text) {
      const { data: res } = await this.$http.post(
        "departmentController/departmentFuzzyByName",
        {
          condition:"department.DeptName",
          name: this.text,
          pageNum: 1,
          pageSize: 10,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      console.log(res.data.list);
      this.departmentInformation = res.data.list;
      this.pageNum = res.data.pageNum;
      this.total = res.data.total;
      this.totalPage = res.data.totalPage;
    },
    //获取科室信息列表
    async addDepartment() {
      const { data: res } = await this.$http.post(
        "departmentController/selectDeptTypeList"
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      console.log(res.data);
      this.deptTypeList = res.data;
    },
    //根据id查询科室分类明细（新）
    async SelectDepartmentList() {
        const { data: res } = await this.$http.post(
          "departmentController/selectDeptcategoryid",
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户列表失败！");
        }
        console.log(res.data);
        this.DepartmentList = res.data;
    },

    //批量删除循环
    itemize(val) {
      for (let i = 0; i < this.DepartmentList.length; i++) {
        if (this.DepartmentList[i].id == val) {
          this.itemizes = this.DepartmentList[i].lists;
        }
      }
    },
    //批量删除方法
    deletes() {
      let list = [];
      for (let a in this.multipleSelection) {
        list[a] = this.multipleSelection[a].id;
      }
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.post(
            "departmentController/updateByPrimaryKeyList",
            {
              id: list,
            }
          );

          if (res.meta.status != 200) {
            return this.$message.error("获取用户列表失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.multipleSelection=[];
          this.getUserList();
          console.log(this.multipleSelection);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //批量删除参数赋值
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //勾选分页保存方法
    getRowKey (row) {
      return row.id
    },
   
    //打开新增页面
    add() {
      this.addDialogVisible = true;
    },
    //重置方法
    cancel(formName) {
      this.addDialogVisible = false;
      this.departmentEditor = false;
      this.$refs[formName].resetFields();
    },
    //重置页面数据（添加）
    addDialogVisibleerAddFormRef() {
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields();
    },
    //重置页面数据（修改）
    addDialogVisibleerDepartmentEditorDataRef() {
      this.departmentEditor = false;
      this.$refs.departmentEditorDataRef.resetFields();
    },
    //点击修改赋值页面
    modifyDepartment(value) {
      this.departmentEditor = true;
      console.log(value);
      this.departmentEditorData = {
        deptcode: value.deptcode,
        deptname: value.deptname,
        deptcategoryid: value.depttype,
        id: value.deptcategoryid,
      };
    },
    //根据id删除对象
    deleteDepartment(id) {
      let list = [];
      list[0] = id;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.post(
            "departmentController/updateByPrimaryKeyList",
            {
              id: list,
            }
          );

          if (res.meta.status != 200) {
            return this.$message.error("获取用户列表失败！");
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改方法
    async updateByPrimaryKeySelective() {
      const { data: res } = await this.$http.post(
        "departmentController/updateByPrimaryKeySelective",
        this.departmentEditorData
      );
      if (res.meta.status != 200) {
        return this.$message.error("创建用户失败！");
      }
      this.cancel("addFormRef");
      this.$message({
        message: "添加成功",
        type: "success",
      });
      this.getUserList();
    },
    //添加方法
    async insert() {
      const { data: res } = await this.$http.post(
        "departmentController/insert",
        this.addForm
      );
      if (res.meta.status != 200) {
        return this.$message.error("创建用户失败！");
      }
      this.cancel("addFormRef");
      this.$message({
        message: "添加成功",
        type: "success",
      });
      this.getUserList();
    },
    //文件导出方法 有问题，禁用
    async getSelectExcel(){
      const { data: res } = await this.$http.post("departmentController/getSelectExcel",{
        queryMethod:"SelectDepartmentAll",
      });
      console.log(res.data);
      const blob = new Blob([res.data]);
      const filName = "12.xlsx";
      const elink = document.createElement("a");
      elink.download = filName;
      elink.style.display = "none";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.boby.removeChild(elink);
      if (res.meta.status != 200) {
        return this.$message.error("创建用户失败！");
      }
      this.$message({
        message: "添加成功",
        type: "success",
      });
    },
  },
};
</script>
<style scoped>
.grid-content bg-purple-dark {
  background: #0b4faf;
}
.el-table-column {
  text-align: center;
}
</style>